package com.stevetracey.backup.io.google;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Map;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.api.services.gmail.Gmail;

public class GoogleMail {

	private static Gmail GMAIL;
	
	private static Log log = LogFactory.getLog(GoogleMail.class);
	
	public static void initialise()
	{
		
		// Create a new authorized Gmail API client
	    GMAIL = new Gmail.Builder(Google.httpTransport, Google.JSON_FACTORY, Google.CREDENTIAL)
	        .setApplicationName(Google.APPLICATION_NAME).build();
	    
	}
	
	public static void sendTemplateEmail(String pTo, String pSubject, Map<String, Object> pSubstitutions)
	{
	    Properties props = new Properties();
	    Session session = Session.getDefaultInstance(props, null);

	    MimeMessage email = new MimeMessage(session);
	   

	    try {
	    	 
	    	GoogleMail.class.getClassLoader();
			//String body = FileUtils.readFileToString(new File(Configuration.getValue("summary.email.file")));
	    	String emailTemplatePath = ClassLoader.getSystemResource("BackupReport.htm").getFile();
	    	String body = FileUtils.readFileToString(new File(emailTemplatePath));
		
		for (String key : pSubstitutions.keySet())
		{
			body = body.replaceAll("#"+key+"#", pSubstitutions.get(key).toString());			
		}
	    
		//FileUtils.writeStringToFile(new File("EmailOut.htm"), body);
		//System.exit(0);
		email.setFrom(new InternetAddress("me"));
	    email.addRecipient(javax.mail.Message.RecipientType.TO,
	                       new InternetAddress(pTo));
	    email.setSubject(pSubject);
	    email.setContent(body, "text/html; charset=utf-8");
	    
	    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
	    email.writeTo(bytes);
	    String encodedEmail = com.google.api.client.util.Base64.encodeBase64URLSafeString(bytes.toByteArray());
	    com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
	    message.setRaw(encodedEmail);
	    
	   
	   
			message = GMAIL.users().messages().send("me", message).execute();
		} catch (Exception e) {
			log.error("failed to send email");
			e.printStackTrace();
		}
	    
	}
}
